package com.eascs.ticket.ticket.controller;

import java.text.Format;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.app.context.ConfigContext;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.dao.sql.ObjectSqlBuilder;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.ticket.ticket.form.StatWorkForm;
import com.eascs.ticket.ticket.format.DueDateViewFormat;
import com.eascs.ticket.ticket.format.TitleViewFormat;
import com.eascs.ticket.ticket.service.TicketSearchService;
import com.eascs.web.context.RequestContext;

@Controller
public class StatWorkRestController extends BaseRestController {

	@Inject
	private TicketSearchService ticketSearchService;

	public BaseRestResult<String> test() {
		return BaseRestResult.info("test");
	}

	@RequestMapping("/stat/ajax/work")
	public PaginationRestResult statWork(StatWorkForm statWorkForm) {
		PageResult<Object[]> pageResult = searchTicket(statWorkForm);
		PaginationInfo paginationInfo = buildPaginationInfo(statWorkForm, pageResult);
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	private PageResult<Object[]> searchTicket(StatWorkForm statWorkForm) {
		ObjectSqlBuilder objectSqlBuilder = ObjectSqlBuilder.createWithAppendTo(statWorkForm, ConfigContext.getStringValue("sql.stat.work"), "/**where_append**/");
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, statWorkForm.getPageSize(), statWorkForm.getPageIndex());
		sqlPageQuery.setQuerySql(objectSqlBuilder.getSql());
		sqlPageQuery.addParams(objectSqlBuilder.getParams());
		return this.ticketSearchService.searchTicket(sqlPageQuery);
	}

	private PaginationInfo buildPaginationInfo(StatWorkForm statWorkForm, PageResult<Object[]> pageResult) {
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, new String[] { "项目", "类型", "编号", "标题", "状态", "版本", "验收日期", "经办", "报告人" });
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setUrl(UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "pageIndex", ""));
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setTitleButtons(new Button[] { null, null, ButtonHelper.createOpenButton(null, "/ticket/view/{2}"), null, null, ButtonHelper.createOpenButton(null, "/ticket/view/{9}?fromTicketId=") });
		paginationInfo.setRendTo(statWorkForm.getRender());
		paginationInfo.setFormats(new Format[] { null, null, null, new TitleViewFormat(), null, null, new DueDateViewFormat() });
		return paginationInfo;
	}

}
